<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns='http://www.w3.org/1999/xhtml'
	xmlns:v='urn:schemas-microsoft-com:vml'>

<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8' />
<meta http-equiv='cache-control' content='no-cache' />
<meta http-equiv='expires' content='0' />
<meta name='copyright' content='Copyright (C) XXX Consultants' />
<meta name='robots' content='none' />

<link rel="stylesheet" href="/gts/css/main.css" />
<link rel="shortcut icon" href="/gts/images/favicon.ico"
	type="image/x-icon" />

<title>XXX Tracking System</title>


<!-- Begin Page JavaScript -->
<script src="/gts/js/utils.js" type="text/javascript"></script>
<script
	src='http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1'></script>

<script type="text/javascript">
<!--
var HEADING = new Array('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW' );
var MAX_PUSH_PINS           = 500;
var virtEarthColorIcon      = null;
var virtEarthDetailPoints   = null;
var virtEarthLastEventTime  = '2007/03/13 19:52:46 GMT';
var virtEarthDetailsEnabled = false;
var virtEarthMap            = null;
var virtEarthDrawLayer      = null;
var virtEarthZoneRadiusM    = 700.0;


function vearthShowDetails() {
  var table = document.getElementById('trackMapDataTable');
  if (table == null) { return; }
  var html = '';
  var pt = virtEarthDetailPoints;

  if (virtEarthDetailsEnabled && (pt != null) && (pt.length > 0)) {
    html += '<table cellspacing=0 cellpadding=0 border=1>\n';
    html += '<thead><tr>';
    html += '<th width=25  nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>#</font></b></center></th>';
    html += '<th width=125 nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>Date/Time</font></b></center></th>';
    html += '<th width=75  nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>Code</font></b></center></th>';
    html += '<th width=110 nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>Lat/Lon</font></b></center></th>';
    html += '<th width=60  nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>MPH</font></b></center></th>';
    html += '<th width=250 nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>Address</font></b></center></th>';
    html += '</tr></thead>\n';
    html += '<tbody>\n';
    for (var i = 0; i < pt.length; i++) {
      html += '<tr>';
      html += '<td nowrap><center>' + pt[i].index    + '</center></td>';
      html += '<td nowrap><center>' + pt[i].dateTime + '</center></td>';
      html += '<td nowrap><center>' + pt[i].code     + '</center></td>';
      html += '<td nowrap><center>' + pt[i].latlon   + '</center></td>';
      html += '<td nowrap><center>' + pt[i].velocity + '</center></td>';
      html += '<td nowrap>' + pt[i].address  + '&nbsp;</td>';
      html += '</tr>\n';
    }
    html += '</tbody>\n';
    html += '</table>\n';
  }
  table.innerHTML = html;
}


function vearthDetailPoint(dev, lat, lon, ndx, code, dtime, spd, hdg, alt, addr) {
  var spdfmt    = numFormatFloat(spd,1);
  if (spd >= 0.1) { spdfmt += ' ' + hdg; };
  this.device   = dev;
  this.latlon   = numFormatFloat(lat,4) + '/' + numFormatFloat(lon,4);
  this.index    = ndx;
  this.code     = code;
  this.dateTime = dtime;
  this.velocity = spdfmt;
  this.altitude = alt;
  this.address  = addr;
}
function vearthInit() {
  if (virtEarthColorIcon == null) {
    virtEarthColorIcon = new Array(
      'http://labs.google.com/ridefinder/images/mm_20_black.png',
      'http://labs.google.com/ridefinder/images/mm_20_brown.png',
      'http://labs.google.com/ridefinder/images/mm_20_red.png',
      'http://labs.google.com/ridefinder/images/mm_20_orange.png',
      'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
      'http://labs.google.com/ridefinder/images/mm_20_green.png',
      'http://labs.google.com/ridefinder/images/mm_20_blue.png',
      'http://labs.google.com/ridefinder/images/mm_20_purple.png',
      'http://labs.google.com/ridefinder/images/mm_20_gray.png',
      'http://labs.google.com/ridefinder/images/mm_20_white.png'
    );
  }
  
  if (virtEarthMap == null) {
    virtEarthMap = new VEMap('verth');
    virtEarthMap.SetDashboardSize(VEDashboardSize.Small);  
    virtEarthMap.LoadMap();        
    virtEarthMap.SetMapMode(VEMapMode.Mode2D);
  
    virtEarthDrawLayer = new VEShapeLayer();
    virtEarthMap.AddShapeLayer(virtEarthDrawLayer);
    document.getElementById('verth').style.cursor='crosshair';
  }
  
  virtEarthMap.AttachEvent('onmousemove', EventHandler_OnMouseMove);
}


function vearthCreatePushPin(dev,lat,lon,ndx,length,icon,date,time,spd,hdg) {
    var flat   = numFormatFloat(lat,4);
    var flon   = numFormatFloat(lon,4);
            
    var spdfmt = spd + ' mph';
    if (spd >= 0.1) { spdfmt += ' ' + hdg; };
    
    var html = '';
    html += '<table>';    
    html += '<tr><td align=left nowrap><small>' + date + ' ' + time + '</small></td></tr>';
    html += '<tr><td align=left nowrap><small>GPS: ' + flat + ' / ' + flon + '</small></td></tr>';
    html += '<tr><td align=left nowrap><small>Speed: ' + spdfmt + '</small></td></tr>';
    html += '</table>';
    var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(lat,lon));
    pin.SetTitle('<small>[#' + ndx + '] <b> device ' + dev + ' : ' + icon + '</b></small>');    

    
    pin.SetDescription(html);
    var pushPinURL = vearthGetIcon(length, icon);
    var imgURL = "<div style='position: relative; top: -6px; left: 6px'><img src='"+pushPinURL+"'></div>";
    pin.SetCustomIcon(imgURL);
    return pin;
}

function vearthGetIcon(length, icon) {
  if(icon==length-1){
  	return virtEarthColorIcon[1];
  }  
  if (icon == 0){
    return virtEarthColorIcon[2];
  } else {
    return virtEarthColorIcon[5];
  }
}

function vearthSetMap(recenter,centerLat,centerLon,pointList, zoomFactor,inclLine) {
  //set center
  var ct = new VELatLong(centerLat, centerLon);
  if (recenter && ((centerLat != 0) || (centerLon != 0))) {
    if (zoomFactor > 0) {
      virtEarthMap.SetCenterAndZoom(ct, zoomFactor);
    } else {
      virtEarthMap.SetMapView(pointList);
    }
  } else {
      virtEarthMap.SetCenter(ct);
  }
}


function vearthGetXMLHttpRequest() {
  var req = null;
  if (window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch(e) {
      req = null;
    }
  } else 
  if (window.ActiveXObject) {
    try {
      req = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
      try {
        req = new ActiveXObject('Microsoft.XMLHTTP');
      } catch(e) {
        req = null;
      }
    }
  } else {
    req = null;
  }
  return req;
}

function drawGeozones(myJSONtext,recenter){
	try{
	var jsonText = eval("("+myJSONtext+")"); 
	}catch(e){
		alert(e);
	}	
	if(jsonText){
		//alert(jsonText);
		var len = jsonText.length;		
		for(var i=0;i<len;i++){
			var gone = jsonText[i];
			var latMin = gone.latitudeMin;
			var latMax = gone.latitudeMax;
			var lonMin = gone.longitudeMin;
			var lonMax = gone.longitudeMax;
			
			var point1 = new VELatLong(latMin,lonMin);
			var point2 = new VELatLong(latMax,lonMin);
			var point3 = new VELatLong(latMax,lonMax);
			var point4 = new VELatLong(latMin,lonMax);
			
			var points = [];
			points.push(point1); 
			points.push(point2);
			points.push(point3);
			points.push(point4);
			
			var myShape = new VEShape(VEShapeType.Polygon, points);		
			virtEarthDrawLayer.AddShape(myShape);
		}		
		
	}else{
	}	
}



//FIXME ajax result parser 
function handle(myJSONtext, recenter){

	virtEarthDetailPoints = [];
		
	try{
	var jsonTextArray = eval("("+myJSONtext+")"); 
	}catch(e){
	alert(e);
	//FIXME return;
	} 

   	var maxLat = -90.0, maxLon = -180.0;
   	var minLat =  90.0, minLon =  180.0;
   	
  	  virtEarthMap.DeleteAllShapes();
   	  virtEarthMap.DeleteAllPolylines();

		
	if(jsonTextArray !=null){		
		// var responseJson = document.getElementById('responseJson');
		// responseJson.innerHTML=myJSONtext;

    	var centerLat = 0.0;
    	var centerLon = 0.0;
    	var zoomFactor = -1;
    	var lastDev = '';
    	
		var count = 0;

	var troutes = jsonTextArray.length;

	var pointList = []
		    	  
    for(ji=0;ji<troutes;ji++) { // begin outer for
    	    
    	var  jsonText =  jsonTextArray[ji]; 	
	 	var detailList = [];
    	pointList = [];
    	var pushPinList = [];
    	var rcdNdx = 0;
    	for(i=0; i<jsonText.length; ++i){	// begin inner for  
	  		var evRcd = jsonText[i];
			var dev   = evRcd.device;
            var date  = evRcd.dateCreated;
            var time  = evRcd.timestamp;            
            var dtime = date;            
            var code  = evRcd.statusCode;
            var icon  = 1 ; //FIXME
            var lat   = evRcd.latitude;
            var lon   = evRcd.longitude;
            var kph   = evRcd.speed;
            var spd   = kph;  //* 0.621371192237334;
            var hdg   = HEADING[Math.round((evRcd.heading+22.5)/45.0) % 8];
            var alt   = evRcd.altitude;
            var addr  = evRcd.address;  
			           
            rcdNdx++;
            count++;
            
            if ((lat != 0) || (lon != 0)) {
              if (lat > maxLat) { maxLat = lat; }
              if (lat < minLat) { minLat = lat; }
              if (lon > maxLon) { maxLon = lon; }
              if (lon < minLon) { minLon = lon; }             
              
              var point = new VELatLong(lat,lon)
              pointList.push(point);
              
              var x = new vearthCreatePushPin(dev,lat,lon,rcdNdx,jsonText.length,i,date,time,spd,hdg)                             
              pushPinList.push(x);              
            }
            
            var vdp = new vearthDetailPoint(dev,lat,lon,rcdNdx,code,dtime,spd,hdg,alt,addr)
            detailList.push(vdp);
            virtEarthDetailPoints.push(vdp);
            
            if (lastDev != null) {
              if (lastDev == '') {
                lastDev = dev;
              } else if (lastDev != dev) {
                lastDev = null;
              }
            }            
        
		}//end inner for			
		
		//troutes		 		 			
		var linecolor = new VEColor(Math.round(255*(ji+1)/troutes),Math.round(5+100*(ji+1)/troutes),Math.round(15+100*(ji+1)/troutes),1); 	
			 			
	  	virtEarthMap.AddPolyline(new VEPolyline('routeLine'+ji,pointList,linecolor, 2));
	  		
		if (pushPinList != null) {
		     for (var i = 0; i < pushPinList.length; i++) {
		           virtEarthMap.AddShape(pushPinList[i]);
		 	}
  		 }
		
		} //end outer for 
		
		centerLat = 0.0;
      	centerLon = 0.0;
      	zoomFactor = -1;
      	
      	if (count <= 0) {
      		centerLat = 37.0;
      		centerLon = -118.0;
      		zoomFactor = 7.0;
    	}   
    
     	//var maxLat = -90.0, maxLon = -180.0;
   		//var minLat =  90.0, minLon =  180.0;
    vearthSetMap(true,(maxLat+minLat)/2,(maxLon+minLon)/2,pointList, 8,true);
    
    vearthShowDetails();    
    
    return virtEarthDetailPoints.length;	
		
	}else{
		return 0;	
	}
}

//XXX  ajax call
function vearthLoadPoints(mapURL,recenter) {
  var req = vearthGetXMLHttpRequest();
  if (req) {
    req.open('GET', mapURL, true);
    req.onreadystatechange = function() {
      if (req.readyState == 4) {        
        handle(req.responseText,recenter)
      } else
      if (req.readyState == 1) {
      } else {
      }
    }
    req.send(null);
  } else {
  }
}
function vearthCreateCircle(pt,radiusMeters) {
  var radLat = geoRadians(pt.Latitude);
  var radLon = geoRadians(pt.Longitude);
  var d = radiusMeters / EARTH_RADIUS_METERS;
  var circlePoints = new Array();
  for (x = 0; x <= 360; x += 3) {
    var xrad   = geoRadians(x);
    var tmpLat = Math.asin(Math.sin(radLat) * Math.cos(d) + Math.cos(radLat) * Math.sin(d) * Math.cos(xrad));
    var tmpLon = radLon + Math.atan2(Math.sin(xrad) * Math.sin(d) * Math.cos(radLat), Math.cos(d)-Math.sin(radLat) * Math.sin(tmpLat));
    circlePoints.push(new VELatLong(geoDegrees(tmpLat),geoDegrees(tmpLon)));
  }
  var circleShape = new VEShape(VEShapeType.Polygon, circlePoints);
  circleShape.SetTitle('<small><b>' + pt.Latitude + ' / ' + pt.Longitude + '</b></small>');
  circleShape.HideIcon();
  circleShape.SetLineWidth(1);
  return circleShape;
}

function EventHandler_OnMouseUp(e) {
}
function EventHandler_OnMouseMove(e) {
  var latLon = virtEarthMap.PixelToLatLong(new VEPixel(e.mapX,e.mapY));
  var locDisp = document.getElementById('trackMapLatLonDisplay');
  if (locDisp != null) { locDisp.innerHTML = numFormatFloat(latLon.Latitude,4)+' / '+numFormatFloat(latLon.Longitude,4); }
  if (e.rightMouseButton == false) {
    document.getElementById('verth').style.cursor='crosshair';
    return false;
  } else {
    return true;
  }
}
function EventHandler_OnClick(e) {
  if (e.rightMouseButton) {
    var x = e.mapX, y = e.mapY;
    var latLon = virtEarthMap.PixelToLatLong(new VEPixel(x,y));
    virtEarthDrawLayer.DeleteAllShapes();
    virtEarthDrawLayer.AddShape(vearthCreateCircle(latLon,virtEarthZoneRadiusM));
    var zoneLat = document.getElementById('trackMapZoneLatitude');
    if (zoneLat != null) { zoneLat.value = latLon.Latitude; }
    var zoneLon = document.getElementById('trackMapZoneLongitude');
    if (zoneLon != null) { zoneLon.value = latLon.Longitude; }
  }
}
var recursiveRefresh = 0;


// XXX mapProviderUpdateMap
function mapProviderUpdateMap(mapURL,recenter) {

  if (recursiveRefresh != 0) { return; }
  recursiveRefresh++;
  try {
    vearthInit();
    vearthLoadPoints(mapURL,recenter);
  } catch(e) {
  }
  recursiveRefresh--;
}

function mapProviderToggleDetails() {
   virtEarthDetailsEnabled = !virtEarthDetailsEnabled;
   vearthShowDetails();
}
function mapProviderUnload() {
	// bla bla
	var a = 1+1;
}
//-->

</script>


<script type="text/javascript">
<!--
function trackMapOnLoad() {
  //calInit();
  trackMapUpdateMap(true);
}
function trackMapOnUnload() {
  mapProviderUnload();
}



function enableGeozone(){
   //FIXME add a page button to enable/disable this  
    var geozoneurl = '/gts/device/getGeozonesAjax?id='+"${devicegroup?.id}"
    var req = vearthGetXMLHttpRequest();
    if (req) {
        req.open('GET', geozoneurl, true);
        req.onreadystatechange = function() {
              if (req.readyState == 4) {
                drawGeozones(req.responseText,true)
              } else  if (req.readyState == 1) {
              } else {
      		  }
    		}
    	req.send(null);
  	} else {  	
  	}
}


function trackMapSubmitCommand(page, cmd, arg) {
  document.CommandForm.page.value = page;
  document.CommandForm.page_cmd.value = cmd;
  document.CommandForm.page_cmd_arg.value = arg;
  document.CommandForm.date_fr.value = calGetFrDay();
  document.CommandForm.date_to.value = calGetToDay();
  document.CommandForm.date_tz.value = calGetTimeZone();
  document.CommandForm.submit();
}

function trackMapNewDevice() {
  document.NewDeviceForm.date_fr.value = calGetFrDay();
  document.NewDeviceForm.date_to.value = calGetToDay();
  document.NewDeviceForm.date_tz.value = calGetTimeZone();
  document.NewDeviceForm.submit();
}

var _uniqueURL = 0;

//onload 
function trackMapUpdateMap(recenter) {
  var dev = ${devicegroup.id};
  //var rfr = calGetFrDay() + '/' + calGetFrTime(false);
  //var rto = calGetToDay() + '/' + calGetToTime(false);
  //var unq = ++_uniqueURL;
  
  var url = '/gts/devicegroup/trackAjax?id='+dev;
  mapProviderUpdateMap(url,recenter);
}
//-->
</script>
<!-- End Page JavaScript -->

</head>

<body onload="javascript:trackMapOnLoad();" leftmargin='0'
	rightmargin='0' topmargin='0' bottommargin='0'>

<div id="spinner" class="spinner" style="display: none;"><img
	src="/gts/images/spinner.gif" alt="Spinner" /></div>

<div class="logo"><img src="/gts/images/grails_logo.jpg"
	alt="Grails" /></div>


<div class="nav"><span class="menuButton"><a class="home"
	href="${createLinkTo(dir:'')}">Home</a></span> <span class="menuButton"><g:link
	class="list" controller="devicegroup" action="list">Devicegroup List</g:link></span>
<span class="menuButton"><g:link class="create"
	controller="devicegroup" action="create">New Devicegroup</g:link></span></div>

<div class="body" style="float: left;">
<h1>Show DeviceGroup</h1>
<g:if test="${flash.message}">
	<div class="message">${flash.message}</div>
</g:if>


<div class="devicecontent" style="float: left;">
<ul style="float: left; text-align: right;">

	<li>Id:</li>

	<li>User:</li>

	<li>Date Created:</li>

	<li>Description:</li>

	<li>Last Updated:</li>

	<li>Devices:</li>

</ul>

<ul style="float: left; list-style-type: none;">
	<li>${devicegroup.id}</li>

	<li><g:link controller="user" action="show"
		id="${devicegroup?.user?.id}">${devicegroup?.user}</g:link></li>

	<li>${devicegroup.dateCreated}</li>

	<li>${devicegroup.description}</li>


	<li>${devicegroup.lastUpdated}</li>

	<li>
	<ul>
		<g:each var="d" in="${devicegroup.devices}">
			<li><g:link controller="track" action="track" id="${d.id}">Track ${d.imeiNumber}</g:link></li>
		</g:each>
	</ul>

	</li>

</ul>

</div>

<div id='verth' style='position: relative; width: 680px; height: 420px;'></div>
<div><b>Location Details</b>&nbsp;&nbsp(<a
	href='javascript:mapProviderToggleDetails()'>toggle show</a>) <span
	id='trackMapDataTable' style='margin-left: 15px;'></span></div>
<div id="responseJson"></div>

</div>
</body>


